####### Tables ########


rm(list=ls())
dev.off()

## Libraries
library(data.table)
library(lfe)
library(multiwayvcov)
library(lmtest)

library(dplyr)
library(raster)
library(stringr)
library(abjutils)

library(stargazer)

source("paysdetat_functions.R")

#### DATA ######

load("livingstandards_data.RData")
load("rebellion_data.RData")
load("grievance_data.RData")
load("grievlevel_data.RData")

## Remove pays d'imposition and ambiguous province Venaissin ##
dat <- reb[generalite!="Venaissin",]
reb <- reb[imposition==0,]

te <- te[imposition==0,]
n <- n[imposition==0,]
p <- p[imposition==0,]


##### Table 3 : RD: Local rule and living standards #####

labs <- c("tall soldiers","age at death","food riots","city growth","urban","tall conscripts","age at death")

#Added dist Paris so results are slightly different
controls <- c("wheat","rugged","distparis","distriver","distsea","distforeignborder","cities_10_50km_1400")

modelsrd <- list(
  rdmodel(height[imposition==0,], "heightcm", bw=50*1000, cont=c(controls,"latitude*longitude"), loc="factor(birthdec)+nearET+longitude+latitude",summary=F),
  rdmodel(decesrural[imposition==0 & decade_dec<790,], "age_an", bw=50*1000, cont=c(controls,"X*Y"), loc="nearET+X+Y+factor(decade_dec)",summary=F), #
  rdmodel(reb[imposition==0,], "subsrebel", bw=50*1000, cont=c(controls,"latitude*longitude"), loc="nearET+longitude+latitude",summary=F),
  rdmodel(cities[imposition==0,], "gX1800", bw=50*1000, cont=c(controls,"X*Y"), loc="nearET+X+Y",summary=F),
  rdmodel(urbarr[imposition==0,], "upop1793arr", bw=50*1000, cont=c(controls,"x*y"), loc="nearET+x+y",summary=F),
  rdmodel(popconscrits[imposition==0,], "grandshare", bw=50*1000, cont=c(controls,"x*y"), loc="nearET+x+y",summary=F),
  rdmodel(decesrural[imposition==0 & decade_dec>=790,], "age_an", bw=50*1000, cont=c(controls,"X*Y"), loc="nearET+X+Y+factor(decade_dec)",summary=F)
)

gs <- lapply(modelsrd, FUN=function(x){x$clustervar$generalite %>% levels %>% length}) %>% unlist

ns <- c(
  length(unique(height[imposition==0 & distestate<50000,locid])),
  length(unique(decesrural[imposition==0 & decade_dec<790 & distestate<50000,com])),
  length(unique(reb[imposition==0 & distestate<50000,city_code])),
  length(unique(cities[imposition==0 & distestate<50000,city])),
  length(unique(urbarr[imposition==0 & distestate<50000 & !is.na(upop1793arr),arrs])),
  length(unique(popconscrits[imposition==0 & distestate<50000,cantid])),
  length(unique(decesrural[imposition==0 & decade_dec>=790 & distestate<50000,com]))
)

ns <- lapply(list(height[imposition==0 & distestate<50000,locid],
                  decesrural[imposition==0 & decade_dec<790 & distestate<50000,com],
                  reb[imposition==0 & distestate<50000,city_code],
                  cities[imposition==0 & distestate<50000,city],
                  urbarr[imposition==0 & distestate<50000 & !is.na(upop1793arr),arrs],
                  popconscrits[imposition==0 & distestate<50000,cantid],
                  decesrural[imposition==0 & decade_dec>=790 & distestate<50000,com]),
             FUN=function(x) length(unique(x))) %>% unlist

ns <- format(ns,big.mark=",")

labs <- c("tall soldiers","age at death","food riots","city growth","urban","tall conscripts","age at death")

stargazer(modelsrd, keep="until1789",type="text", 
          float=F,
          out="rd_econdev_50.tex",
          column.separate = c(3,4),column.labels = c("Ancien Regime","post-1789"),
          dep.var.labels = labs, 
          omit.stat = "ser",
          omit.table.layout  = "n",
          add.lines = list(c("Timeframe","1716-1784","1740-1790","1661-1788","1700-1800","1793","1818-1830","1800-1829"),
                           c("Geographic unit","commune","commune","commune","city","arr.","canton","commune"),
                           c("Locations",ns)))

##### Table 4: RD: Local rule and dissatisfaction with royal taxation ########

controls <- c("wheat","rugged","distparis","distsea","distriver","distforeignborder","cities_10_50km_1400","latitude","longitude","latitude*longitude")

#Grievances
dats <- list(te,p,n)
models2 <- lapply(dats,as.data.frame) %>%
  lapply(.,FUN=rdmodel,depvar="taxall_s",treat="until1789", clust="generalite",cont=controls,loc="",summary=F)

ms2 <- lapply(dats, FUN=function(x){mean(x[,taxall_s],na.rm=T)}) %>% unlist %>% round(digits=3)
ns2 <- lapply(dats, FUN=nrow) %>% unlist
gs2 <- lapply(dats, FUN=function(x){length(unique(x$generalite))}) %>% unlist

# Social conflict 
models1 <- lapply(c("fiscalrebel","fiscalnosaltrebel"),FUN=rdmodel,datause=reb,treat="until1789",clust="generalite",cont=controls,loc="",summary=F)

ms1 <- lapply(c("fiscalrebel","fiscalnosaltrebel"),FUN=function(x){mean(reb[,get(x)])}) %>% unlist %>% round(digits=3)
ns1 <- rep(nrow(reb),2)
gs1 <- rep(length(unique(dat$generalite)),2)

stargazer(models1,models2, keep="until1789",
          out = "ols_tax.tex",
          float=F,
          covariate.labels = "local rule", 
          dep.var.labels.include = F,
          column.separate = c(2,3),
          column.labels  = c("Rebellions","Grievances"),
          add.lines = list(c("mean dep var",ms1,ms2),
                           c("N",ns1,ns2),
                           c("N cluster",gs1,gs2)),
          omit.table.layout = "sn",
          type="text")

##### Table 5: OLS: Local rule and dissatisfaction with local elites ########

# Social conflict 
models1 <- lapply(c("seignrebel","localrebel"),FUN=rdmodel,datause=reb,treat="until1789",clust="generalite",cont=controls,loc="",summary=F)

ms1 <- lapply(c("seignrebel","localrebel"),FUN=function(x){mean(reb[,get(x)])}) %>% unlist %>% round(digits=3)
ns1 <- rep(nrow(reb),2)
gs1 <- rep(length(unique(dat$generalite)),2)

#Grievances
dats <- list(te,p,te[veto==0 & nearET!="S",],p[veto==0 & nearET!="S",])
models2 <- lapply(dats,as.data.frame) %>%
  lapply(.,FUN=rdmodel,depvar="seignsse_s",treat="until1789",clust="generalite",cont=controls,loc="",summary=F)
models2 <- lapply(dats,as.data.frame) %>%
  lapply(.,FUN=rdmodel,depvar="seignsse_s",treat="until1789",clust="generalite",cont=controls,loc="",summary=F)

ms2 <- lapply(dats, FUN=function(x){mean(x[,seignsse_s],na.rm=T)}) %>% unlist %>% round(digits=3)
ns2 <- lapply(dats, FUN=nrow) %>% unlist
gs2 <- lapply(dats, FUN=function(x){length(unique(x$generalite))}) %>% unlist

stargazer(models1,models2, keep="until1789",
          out = "ols_elites.tex",
          float=F,
          covariate.labels = "local rule", 
          dep.var.labels.include = F,
          column.separate = c(2,4),
          column.labels  = c("Rebellions","Grievances"),
          add.lines = list(c("Consent institutions included","All","All","All","All","Weak","Weak"),
                           c("mean dep var",ms1,ms2),
                           c("N",ns1,ns2),
                           c("N cluster",gs1,gs2)),
          omit.table.layout = "sn",
          type="text")



##### Table B.2. Summary statistics: rebellions ########

jn[,riot_type:=rm_accent(riot_type)]

counts <- lapply(c("fiscal","seign","notable","municip","glise","ubsist","judiciaire","reform","eligion","travail","region","ivers"),
                 FUN=function(x){jn[,sum(grepl(pattern=x,riot_type))]})
shares <- unlist(counts)/nrow(jn)*100

names <- lapply(c("fiscal","seign","notable","municip","glise","ubsist","judiciaire","reform","eligion","travail","region","ivers"),
                FUN=function(x){jn[,unique(grep(pattern=x,riot_type,v=T))]})

names <- str_split(unlist(names),"\\:",simplify=T)[,2] %>% str_trim

tab <- data.table("Riot type"=names, "Count"=unlist(counts), "Freq."=shares)

stargazer(tab, summary=F, type="text", out="summarystats_conflict.tex")

##### Table B.6: Summary statistics: grievances #########
#load("grievlevel_data.RData")

makepanel <- function(dat){dat <- dat[,.(n_griev=length(griev_c_f4),
                                         gov=sum(as.numeric(grepl("^G",griev_c_f4))),
                                         const=sum(as.numeric(grepl("^C",griev_c_f4))),
                                         econ=sum(as.numeric(grepl("^E",griev_c_f4))),
                                         just=sum(as.numeric(grepl("^J",griev_c_f4))),
                                         rel=sum(as.numeric(grepl("^R",griev_c_f4))),
                                         soc=sum(as.numeric(grepl("^S",griev_c_f4))),
                                         gta=sum(as.numeric(grepl("^GTA",griev_c_f4))),
                                         seign=sum(as.numeric(grepl("^(JCSC|SSE|EAGCRSC|EAGCRSE)",griev_c_f4)))),
                                      keyby=c("doc_id_b_no","imposition","until1789")]

tab <- lapply(dat[until1789==0 & imposition==0,-c("doc_id_b_no","imposition","until1789")],FUN=function(x){c(length(x),mean(x),sd(x),min(x),max(x))})
tab <- do.call(rbind,tab) %>% as.data.table
names(tab) <- c("N","mean","sd","min","max")
tab0 <- tab

tab <- lapply(dat[until1789==1 & imposition==0,-c("doc_id_b_no","imposition","until1789")],FUN=function(x){c(length(x),mean(x),sd(x),min(x),max(x))})
tab <- do.call(rbind,tab) %>% as.data.table
names(tab) <- c("N","mean","sd","min","max")
tab1 <- tab

vars <- c("N grievances","Government","Constitution","Economy","Justice","Religion","Society","Taxation","Seigneurial regime")
stargazer(data.table(vars,tab0,tab1), summary=F, type="text")
}

makepanel(t_bygriev) #Panel A (Third Estate)
makepanel(n_bygriev) #Panel B (Nobility)

#Panel C (Parishes)
p_bygriev <- p_bygriev[,.(n_griev=length(griev_c_f4),
                          gov=sum(as.numeric(grepl("^G",griev_c_f4))),
                          const=sum(as.numeric(grepl("^C",griev_c_f4))),
                          econ=sum(as.numeric(grepl("^E",griev_c_f4))),
                          just=sum(as.numeric(grepl("^J",griev_c_f4))),
                          rel=sum(as.numeric(grepl("^R",griev_c_f4))),
                          soc=sum(as.numeric(grepl("^S",griev_c_f4))),
                          gta=sum(as.numeric(grepl("^GTA",griev_c_f4))),
                          seign=sum(as.numeric(grepl("^(JCSC|SSE|EAGCRSC|EAGCRSE)",griev_c_f4)))),
                       keyby=c("doc_id_b_no","doc_id_serial_no","imposition","until1789")]

tab <- lapply(p_bygriev[until1789==0 & imposition==0,-c("doc_id_b_no","doc_id_serial_no","imposition","until1789")],FUN=function(x){c(length(x),mean(x),sd(x),min(x),max(x))})
tab <- do.call(rbind,tab) %>% as.data.table
names(tab) <- c("N","mean","sd","min","max")
tab0 <- tab

tab <- lapply(p_bygriev[until1789==1 & imposition==0,-c("doc_id_b_no","imposition","until1789")],FUN=function(x){c(length(x),mean(x),sd(x),min(x),max(x))})
tab <- do.call(rbind,tab) %>% as.data.table
names(tab) <- c("N","mean","sd","min","max")
tab1 <- tab
vars <- c("N grievances","Government","Constitution","Economy","Justice","Religion","Society","Taxation","Seigneurial regime")
stargazer(data.table(vars,tab0,tab1), summary=F, type="text", out="summarystats_grievances.tex")

##### Table E.1: OLS: Local rule and living standards ############

labs <- c("tall soldiers","age at death","food riots","city growth","urban","tall conscripts","age at death")

#Added dist Paris so results are slightly different
controls <- c("wheat","rugged","distparis","distriver","distsea","distforeignborder","cities_10_50km_1400")

models <- list(
  rdmodel(height[imposition==0,], "heightcm", bw=10^10, cont=c(controls,"latitude*longitude"), loc="factor(birthdec)+longitude+latitude",summary=F),
  rdmodel(decesrural[imposition==0 & decade_dec<790,], "age_an", bw=10^10, cont=c(controls,"X*Y"), loc="X+Y+factor(decade_dec)",summary=F),
  rdmodel(reb[imposition==0,], "subsrebel", bw=10^10, cont=c(controls,"latitude*longitude"), loc="longitude+latitude",summary=F),
  rdmodel(cities[imposition==0,], "gX1800", bw=10^10, cont=c(controls,"X*Y"), loc="X+Y",summary=F),
  rdmodel(urbarr[imposition==0,], "upop1793arr", bw=10^10, cont=c(controls,"x*y"), loc="x+y",summary=F),
  rdmodel(popconscrits[imposition==0,], "grandshare", bw=10^10, cont=c(controls,"x*y"), loc="x+y",summary=F),
  rdmodel(decesrural[imposition==0 & decade_dec>=790,], "age_an", bw=10^10, cont=c(controls,"X*Y"), loc="X+Y+factor(decade_dec)",summary=F)
)

gs <- lapply(models, FUN=function(x){x$clustervar$generalite %>% levels %>% length}) %>% unlist

ns <- c(
  length(unique(height[imposition==0 & distestate<10^10,locid])),
  length(unique(decesrural[imposition==0 & decade_dec<790 & distestate<10^10,com])),
  length(unique(reb[imposition==0 & distestate<10^10,city_code])),
  length(unique(cities[imposition==0 & distestate<10^10,city])),
  length(unique(urbarr[imposition==0 & distestate<10^10 & !is.na(upop1793arr),arrs])),
  length(unique(popconscrits[imposition==0 & distestate<10^10,cantid])),
  length(unique(decesrural[imposition==0 & decade_dec>=790 & distestate<10^10,com]))
)
ns <- format(ns,big.mark=",")

stargazer(models, keep="until1789",type="text", 
          float=F,
          out="ols_econdev.tex",
          covariate.labels = "localrule",
          column.separate = c(3,4),column.labels = c("Ancien Regime","post-1789"),
          dep.var.labels = labs, 
          omit.stat = "ser",
          omit.table.layout  = "n",
          add.lines = list(c("Timeframe","1716-1784","1740-1790","1661-1788","1700-1800","1793","1818-1830","1800-1829"),
                           c("Geographic unit","commune","commune","commune","city","arr.","canton","commune"),
                           c("Locations",ns)))


##### Table F.1: Local rule and level of detail in the rebellion dataset #####

jn[,nb:=as.numeric(as.character(nb_participants))]
jn[,missingnum:=as.numeric(is.na(nb))]
jn[pop1793==0,pop1793:=NA]

models<- list(
  felm(missingnum ~ until1789 + log(pop1793) +rugged + wheat + distparis + cities_10_50km_1400 | 0 | 0 | generalite, data=jn[imposition==0 & year %in% 1661:1788,]),
  felm(missingnum ~ until1789 + log(pop1793) + rugged + wheat + distparis + cities_10_50km_1400 | 0 | 0 | generalite, data=jn[imposition==0 & year %in% 1661:1788 & fiscal>0,]),
  felm(missingnum ~ until1789 + log(pop1793) + rugged + wheat + distparis + cities_10_50km_1400 | 0 | 0 | generalite, data=jn[imposition==0 & year %in% 1661:1788 & fiscalnosalt>0,]),
  felm(missingnum ~ until1789 + log(pop1793) + rugged + wheat + distparis + cities_10_50km_1400 | 0 | 0 | generalite, data=jn[imposition==0 & year %in% 1661:1788 & local>0,]),
  felm(missingnum ~ until1789 + log(pop1793) + rugged + wheat + distparis + cities_10_50km_1400 | 0 | 0 | generalite, data=jn[imposition==0 & year %in% 1661:1788 & seign>0,]))

stargazer(models, keep="until1789", type="text",
          float=F,
          out="missingnum_rebellions.tex",
          dep.var.caption = "Dependent variable: Missing info on riot size",dep.var.labels.include = F,
          covariate.labels = "local rule",
          column.labels = c("All","Fiscal","Fiscal no smuggling","Local elites","Seign. elites"),
          omit.stat = c("adj.rsq","rsq","ser"),
          omit.table.layout  = "n")

##### Table F.2: OLS: Fiscal rebellion and grievance counts #####

controls <- c("wheat","rugged","distparis","distriver","distsea","distforeignborder","cities_10_50km_1400")

#Rebellions
models_rebelcount <- lapply(c("fiscal","fiscalnosalt"),FUN=rdmodel,datause=reb,treat="until1789",clust="generalite",cont=c("rebel",controls),loc="latitude*longitude",summary=F)

ms1 <- lapply(c("fiscal","fiscalnosalt"),FUN=function(x){mean(reb[,get(x)])}) %>% unlist %>% round(digits=3)
ns1 <- rep(nrow(reb),2)
gs1 <- rep(length(unique(dat$generalite)),2)

#Grievances
dats <- list(te,n,p)
models_grievcount <- lapply(lapply(dats,as.data.frame), FUN=rdmodel,depvar="taxall",treat="until1789",clust="generalite",cont=c("n_griev",controls),loc="latitude*longitude",summary=F)

ms2 <- lapply(dats, FUN=function(x){mean(x[,taxall],na.rm=T)}) %>% unlist %>% round(digits=3)
ns2 <- lapply(dats, FUN=nrow) %>% unlist
gs2 <- lapply(dats, FUN=function(x){length(unique(x$generalite))}) %>% unlist

stargazer(models_rebelcount,models_grievcount, keep="until1789",
          out = "ols_tax_count_control.tex",
          float=F,
          covariate.labels = "local rule", 
          dep.var.labels.include = F,
          column.separate = c(2,3),
          column.labels  = c("Rebellions","Grievances"),
          add.lines = list(c("mean dep var",ms1,ms2),
                           c("N",ns1,ns2),
                           c("N cluster",gs1,gs2)),
          omit.table.layout = "sn",
          type="text")

##### Table F.3: OLS: local rule and rebellions (binary outcome) #####
controls <- c("wheat","rugged","distparis","distriver","distsea","distforeignborder","cities_10_50km_1400")

models_rebelbin <- lapply(c("fiscal1","fiscalnosalt1","seign1","local1","subs1"),FUN=rdmodel,datause=reb,treat="until1789",clust="generalite",cont=controls,loc="latitude*longitude",summary=F)

ms1 <- lapply(c("fiscal1","fiscalnosalt1","seign1","local1","subs1"),FUN=function(x){mean(reb[,get(x)])}) %>% unlist %>% round(digits=3)
ns1 <- rep(nrow(reb),5)
gs1 <- rep(length(unique(dat$generalite)),5)

stargazer(models_rebelbin, keep="until1789",
          out = "ols_rebel_dummy.tex",
          float=F,
          covariate.labels = "local rule", 
          dep.var.caption = paste("Dependent variable:"),
          dep.var.labels.include = F,
          column.labels  = c("Fiscal","No smuggling","Seign.","Local elites","Food riots"),
          add.lines = list(c("mean dep var",ms1),
                           c("N",ns1),
                           c("N cluster",gs1)),
          omit.table.layout = "sn",
          type="text")



##### Table F.4. OLS: Main results on grievances (restricted sample) ####

controls <- c("wheat","rugged","distparis","distsea","distriver","distforeignborder","cities_10_50km_1400")
vars <- c("taxall_s","seign_s")

dat <- te[b_id %in% p$b_id,]

m1 <- rdmodel(dat,vars[1],bw=10^10,"until1789",clust="generalite", cont=controls, loc="latitude*longitude", summary=F)
m2 <- rdmodel(dat[veto==0,],vars[1],bw=10^10,"until1789",clust="generalite", cont=controls, loc="latitude*longitude", summary=F)
m3 <- rdmodel(dat[veto==1 | until1789==0,],vars[1],bw=10^10,"until1789",clust="generalite", cont=controls, loc="latitude*longitude", summary=F)

m4 <- rdmodel(dat,vars[2],bw=10^10,"until1789",clust="generalite", cont=controls, loc="latitude*longitude", summary=F)
m5 <- rdmodel(dat[dat$veto==0,],vars[2],bw=10^10,"until1789",clust="generalite", cont=controls, loc="latitude*longitude", summary=F)
m6 <- rdmodel(dat[dat$veto==1 | dat$until1789==0,],vars[2],bw=10^10,"until1789",clust="generalite", cont=controls, loc="latitude*longitude", summary=F)

var <- vars[1]
n1 <- nrow(dat[is.na(dat[,get(var)])==F,])
n2 <- nrow(dat[is.na(dat[,get(var)])==F & veto==0,])
n3 <- nrow(dat[is.na(dat[,get(var)])==F & (veto==1 | until1789==0),])

g1 <- nrow(unique(dat[is.na(get(var))==F,"generalite"]))
g2 <- nrow(unique(dat[veto==0 & is.na(get(var))==F,"generalite"]))
g3 <- length(unique(dat[is.na(get(var))==F & (veto==1 | until1789==0),"generalite"]))

var <- vars[1]
dats <- list(dat[,get(var)],dat[veto==0,get(var)],dat[veto==1|until1789==0,get(var)])
dep1 <- lapply(dats,FUN=mean,na.rm=T) %>% unlist %>% round(digits=3)

var <- vars[2]
dats <- list(dat[,get(var)],dat[veto==0,get(var)],dat[veto==1|until1789==0,get(var)])
dep2 <- lapply(dats,FUN=mean,na.rm=T) %>% unlist %>% round(digits=3)

stargazer(m1,m2,m3,m4,m5,m6, keep="until1789",
          out = "ols_villagesample.tex",
          float=F,
          covariate.labels = "local rule", 
          dep.var.caption = "Dependent variable: share of grievances",
          column.separate = c(3,3),
          column.labels  = c("Taxation","Seigneurial regime"),
          add.lines = list(c("mean dep var",dep1,dep2),
                           c("N",n1,n2,n3,n1,n2,n3),
                           c("N cluster",g1,g2,g3,g1,g2,g3),
                           c("Consent provinces included","All","Weak TE","Strong TE","All","Weak TE","Strong TE")),
          omit.table.layout = "sn",
          type="text")

